#include "mk_auto_mutex.h"
#include "mk_logger.h"
#include <string.h>

#ifndef INFINITE
	#define INFINITE 0xFFFFFFFF 
#endif

#define GLOBAL_STR	"Global\\"

mk_mutex::mk_mutex() :m_mutex(NULL)
{
	memset(_mutex_name,0, sizeof(_mutex_name));
}

mk_auto_mutex::mk_auto_mutex( mk_mutex * mutex_ptr, const char *szMutexName)
{
	Init(mutex_ptr, szMutexName, INFINITE);
}

mk_auto_mutex::mk_auto_mutex( mk_mutex * mutex_ptr)
{
	if(mutex_ptr->m_mutex == NULL)
		mutex_ptr->m_mutex = mutex_create();
	_mutex_ptr = mutex_ptr;
}

mk_auto_mutex::mk_auto_mutex( mk_mutex * mutex_ptr, const char *szMutexName, long timeout )
{
	Init(mutex_ptr, szMutexName, timeout);
}

int mk_auto_mutex::open_mutex(char *szGlobalMutexName)
{
	char globalMutextName[256] = {0};
	if(strstr(szGlobalMutexName, GLOBAL_STR))
	{
		strncpy(globalMutextName, szGlobalMutexName, 256);
	}
	else
	{
		strcpy(globalMutextName, GLOBAL_STR);
		strcat(globalMutextName, szGlobalMutexName);
	}

	return mutex_open(_mutex_ptr->m_mutex, globalMutextName);
}

mk_auto_mutex::~mk_auto_mutex()
{
	if(_mutex_ptr)
	{
		if(_mutex_ptr->m_mutex)
		{
			DBG_LOGMSG("auto unlock");
		}

		mutex_unlock(_mutex_ptr->m_mutex);
	}
}

void mk_auto_mutex::Init(mk_mutex * mutex_ptr, const char *szMutexName, long timeout)
{
	char globalMutextName[256] = {0};

	if(strstr(mutex_ptr->name(), szMutexName) == NULL) //mutex changed
	{
		mutex_destroy(mutex_ptr->m_mutex);
		mutex_ptr->m_mutex = NULL;
		strncpy(mutex_ptr->name(),szMutexName, 256);
	}

	if(mutex_ptr->m_mutex == NULL)
		mutex_ptr->m_mutex = mutex_create();

	if(!mutex_ptr->m_mutex->bInited)
	{
		if(strstr(szMutexName, GLOBAL_STR))
		{
			strncpy(globalMutextName, szMutexName, 256);
		}
		else
		{
			strcpy(globalMutextName, GLOBAL_STR);
			strcat(globalMutextName, szMutexName);
		}

		mutex_init(mutex_ptr->m_mutex, globalMutextName);
	}
	_mutex_ptr = mutex_ptr;
	if(_mutex_ptr->m_mutex->bInited)
	{
		DBG_LOGMSG("auto lock, %s", _mutex_ptr->name());
		mutex_lock(_mutex_ptr->m_mutex, timeout);
	}
}
